package xyz.scootaloo.oj.leetcode

import cn.hutool.core.lang.Console
import org.junit.Test

/**
 * @author flutterdash@qq.com
 * @since 2021/5/9 16:21
 */
class P57 {

    fun insert(intervals: Array<IntArray>, newInterval: IntArray): Array<IntArray> {
        val size = intervals.size
        if (size == 0)
            return arrayOf(newInterval)
        if (newInterval[0] > intervals[size - 1][1]) {
            return Array(size + 1) {
                idx ->
                if (idx == size)
                    newInterval
                else
                    intervals[idx]
            }
        }
        if (newInterval[1] < intervals[0][0]) {
            return Array(size + 1) {
                idx ->
                if (idx == 0)
                    newInterval
                else
                    intervals[idx - 1]
            }
        }


        var left = 0
        for (idx in intervals.indices) {
            if (intervals[idx][0] >= newInterval[0]) {
                left = idx
                intervals[idx][0] = Math.min(newInterval[0], intervals[idx][0])
                break
            }
        }

        var right = left
        for (idx in left until intervals.size) {
            if (intervals[idx][0] > newInterval[1]) {
                right = idx - 1
                intervals[idx - 1][1] = Math.max(intervals[idx - 1][1], newInterval[1])
                break
            }
            if (intervals[idx][1] >= newInterval[1]) {
                right = idx
                break
            }
        }
        // |     |
        // 1, 2, 3, 4, 5
        if (left == right)
            return intervals

        return intervals
    }

    @Test
    fun test0() {
        val intArray = Array<Int>(10) {
            idx ->
            idx + 1
        }
        Console.log(intArray)
    }

}
